<?php


namespace App\Http\Controllers\Admin;
use App\Imports\CarImport;
use App\Models\Appoint;
use App\Models\Car;
use App\Models\Config;
use App\Models\Credit;
use App\Services\CarService;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Redis;

class CarController extends BaseController
{

    public function import() {
        try{
            Excel::import(new CarImport(), request()->file('file'));
            return $this->success([]);
        }catch (\Exception $e) {
            return $this->failed($e->getMessage());
        }
    }

    public function flow(Request $request) {
        $this->validate($request, [
           'car_id' => 'required',
            'status' => 'required|in:1,2,3'
        ]);
        $from = 2;
        $input = $request->input();
        $user = $this->getUser();
        try {
            CarService::flow($input, -$user->id, $from, $user);
            return $this->success([]);
        } catch (\Exception $e) {
            return $this->failed($e->getMessage());
        }
    }

    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $this->validate($request, [
            'carrier_unit' => 'required',
            'car_num' => 'required',
            'trailer_num' => 'required',
            'weight' => 'required',
            'is_cold' => 'required',
            'driver' => 'required',
            'supercargo' => 'required',
            'delivery_unit' => 'required',
            'id' => 'filled|exists:cars'
        ]);
        $input = $request->input();
        $id = \request("id");

        if ($id) {
            unset($input['appoint_user'], $input['sign_in_user'], $input['sign_out_user'], $input['cancel_user']);
             Car::where('id', $id)->update($input);
        } else {
            $history_date = Car::where('date', '>', date('Y-m-d H:i:s'))->orderBy('id', 'desc')->value('date');
            if (!$history_date)
                return $this->failed("请先导入excel");

            $day = diffBetweenTwoDays($history_date, date('Y-m-d'), 0);
            if ($day < 1) {
                return $this->failed("计划日期必须大于今天");
            }
            $input['date'] = $history_date;
            $info = Car::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }

    public function index(Request $request) {
//        $this->validate($request, [
//            'date' => 'required'
//        ]);
        $list = CarService::search_list($request);
        return $this->paginate($list);
    }

    public function appoint_index(Request $request) {
//        $arr = Config::getSiteVal();
//        $appoint = $arr['appoint_basic'];
//        $max_date = max(array_column($appoint, 'end_at'));
//
//        //判断当前是否大于最后面日期，如果大于向后面计算一天
//        $tomorrow = date("Y-m-d",strtotime("+1 day"));
//        if (time() > strtotime($max_date)) {
//            $arr = Config::getSiteVal($tomorrow);
//            $appoint = $arr['appoint_basic'];
//            $max_date = max(array_column($appoint, 'end_at'));
//        }

        $appoint = Config::getAppointTime();
        $select_date = $appoint['val'];

//        $select_date = date('Y-m-d', strtotime($max_date));
        $request->type = 1;
        $request->date = $select_date;

        // 已预约 1, 2, 3, 4
        $list = CarService::search_list($request);
        $extra['publish_total'] = Car::where('cur_date', '=', $select_date)->where('is_publish', 1)->count();
        //排队预约数 = 把总计划数-待预约-已取消
        //带预约数
        $wait_appoint_total = Car::where('cur_date', $select_date)->where('status', Car::STATUS_WAIT_APPOINT)->where('is_publish', 1)->count();
        //已取消数
        $cancel_total = Car::where('cur_date', $select_date)->where('status', Car::STATUS_CANCEL)->where('is_publish', 1)->count();
        $extra['queue_total'] = $extra['publish_total'] - $wait_appoint_total - $cancel_total;
        $extra['cur_date'] = $select_date != '2099-01-01' ? $select_date : '-';
        return $this->paginate($list, $extra);
    }

    public function load_index(Request $request) {
//        $arr = Config::getSiteVal();
//        $load_yesterday_end_at = $arr['load_yesterday_end_at'];
//        $select_date = date('Y-m-d');
//        if (time() <= strtotime($load_yesterday_end_at)) {
//            $select_date = date('Y-m-d', strtotime($load_yesterday_end_at));
//        }
        $loan = Config::isShowLoad();
        $select_date = $loan['val'];


        $request->type = 1;
        $request->date = $select_date;

        // 已预约 1, 2, 3, 4
        $list = CarService::search_list($request);
        $extra['publish_total'] = Car::where('cur_date', '=', $select_date)->where('is_publish', 1)->count();
        //排队预约数 = 把总计划数-待预约-已取消
        //带预约数
        $wait_appoint_total = Car::where('cur_date', $select_date)->where('status', Car::STATUS_WAIT_APPOINT)->where('is_publish', 1)->count();
        //已取消数
        $cancel_total = Car::where('cur_date', $select_date)->where('status', Car::STATUS_CANCEL)->where('is_publish', 1)->count();
        //签到数
        $extra['sign_in_total'] = Appoint::where('date', $select_date)->where('status', 2)->count();
        //签退数
        $extra['sign_out_total'] = Appoint::where('date', $select_date)->where('status', 3)->count();
        //排队数
        $extra['queue_total'] = $extra['publish_total'] - $wait_appoint_total - $cancel_total;

        $extra['wei_yue_total'] = Credit::where('date', $select_date)->count();

        if (!$loan['is_show']) {
            $extra['cur_date'] = '';
        } else {
            $extra['cur_date'] = $select_date;
        }
        return $this->paginate($list, $extra);
    }


    public function clear() {
        Car::where('is_publish', 0)->delete();
        return $this->success([]);
    }


    public function destroy(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:cars'
        ]);
        $id = $request->input('id');
        Car::where('id', $id)->delete();
        return $this->success([]);
    }

    /**
     * 详情
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function info(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:cars'
        ]);
        $id = \request("id");
        $field = ['nickname', 'title'];
        $info = Car::withCertain('appoint_user', $field)->withCertain('sign_in_user', $field)
            ->withCertain('sign_out_user', $field)->withCertain('cancel_user', $field)->find($id);
        return $this->success($info);
    }

    public function publish(Request $request) {
        $car = Car::where('is_publish', 0)->first();
        if (!$car)
            return $this->failed('不存在待发布内容');
        $cur_date = $car->cur_date;
        $publish_total = Car::where('is_publish', 0)->count();
        Car::where('is_publish', 0)->update(['is_publish' => 1]);
        $all_total = Car::where('is_publish', 1)->where('cur_date', $cur_date)->count();

        return $this->success(compact('all_total', 'publish_total', 'cur_date'));
    }

    public function clear_future(Request $request) {
        $cur_date = date('Y-m-d');
        Car::where('cur_date', '>', $cur_date)->where('is_publish', 1)->delete();
        Appoint::where('date', '>', $cur_date)->delete();
        return $this->success([]);
    }
}

